<template>
  <div class="app-container home">
    <div class="head">
      <div>请选择日期:</div>
      <el-date-picker
        v-model="dateRange"
        type="daterange"
        range-separator="至"
        start-placeholder="开始日期"
        end-placeholder="结束日期"
        size="medium"
        :picker-options="dateOptions"
        ref="datePicker"
      ></el-date-picker>
      <div>选择区域:</div>
      <el-radio-group v-model="selectMode">
        <el-radio-button label="rect">矩形框选</el-radio-button>
        <el-radio-button label="round">圆形框选</el-radio-button>
      </el-radio-group>
    </div>
    <div id="map" style="height: 0; flex: 1"></div>
  </div>
</template>

<script>
import { baseMap } from "@/utils/map";
import { formatDate } from "@/utils/formatTime";

export default {
  dicts: [],
  components: {},
  data() {
    return {
      map: null,
      tileLayer: null,
      markerLayer: null,
      dateRange: [new Date(), new Date()],
      dateOptions: {
        disabledDate(time) {
          return time >= new Date(formatDate(new Date(), "YYYY-mm-dd"));
        },
      },
      selectMode: "",
      selectedMarker: [],
      boxStart: null,
      boxEnd: null,
    };
  },
  mounted() {
    this.initMap();
    window.addEventListener("resize", this.handleResize);
  },
  beforeDestroy() {
    window.removeEventListener("resize", this.handleResize);
    // this.map.remove();
  },
  methods: {
    initMap() {
      // 初始化地图，并设置地理中心和缩放倍数
      var map = baseMap("map");

      var markers = [
        [29.81, 113.32], // lon, lat
        [29.83, 113.34],
        [29.85, 113.38],
        // 添加更多站点...
      ];
      var markerlayer = L.layerGroup();
      var ico = L.icon({
        iconUrl: require("@/assets/icons/png/wqMonitor.png"),
        iconSize: [35, 42],
        popupAnchor: [0, -20],
      });
      markers.forEach((x) => {
        var marker = L.marker(x, {
          // icon: ico,
          title: "水质监测点",
        });
        Object.defineProperties(marker, { data: { value: x } });
        marker.addTo(markerlayer);
      });
      map.addLayer(markerlayer);
      this.markerLayer = markerlayer;

      // 创建矩形框选区域
      var rectangle;
      map.on("draw:created", function (e) {
        var layer = e.layer;
        rectangle = layer;
        map.addLayer(rectangle);
      });

      this.map = map;
      this.handleResize();
      this.bindEvents();
    },
    handleResize() {
      if (this.map) {
        this.map.invalidateSize();
      }
    },
    bindEvents() {
      this.map.on("mousedown", this.handleMouseDown);
      this.map.on("mouseup", this.handleMouseUp);
    },
    handleMouseDown(e) {
      if (this.selectMode) {
        this.boxStart = e.latlng;
        this.boxEnd = this.boxStart;
        this.map.dragging.disable();
        L.rectangle(
          [
            [this.boxStart.lat, this.boxStart.lng],
            [this.boxEnd.lat, this.boxEnd.lng],
          ],
          { color: "red", weight: 2 }
        ).addTo(this.map);
        this.map.on("mousemove", this.handleMouseMove);
      }
    },
    handleMouseMove(e) {
      this.boxEnd = e.latlng;
      const bounds = L.latLngBounds(this.boxStart, this.boxEnd);
      this.map.eachLayer((layer) => {
        if (layer instanceof L.Rectangle) {
          layer.setBounds(bounds);
        }
      });
    },
    handleMouseUp() {
      if (this.selectMode) {
        this.map.off("mousemove", this.handleMouseMove);
        this.map.dragging.enable();
        this.querySites();

        var bound = null;
        this.map.eachLayer((layer) => {
          if (layer instanceof L.Rectangle) {
            bound = layer;
          }
        });
        if (bound) this.map.removeLayer(bound);

        this.selectMode = "";
        this.boxStart = null;
        this.boxEnd = null;
      }
    },
    // 获取选中矩形的边界，并过滤标记
    querySites() {
      if (!this.boxStart || !this.boxEnd) {
        alert("请先用框选工具选择一个区域！");
        return;
      }

      var bounds = L.latLngBounds(this.boxStart, this.boxEnd);
      var filteredMarkers = [];

      // 遍历所有标记并检查是否在矩形边界内
      this.markerLayer.eachLayer(function (marker) {
        if (bounds.contains(marker.getLatLng())) {
          filteredMarkers.push(marker);
          marker.setIcon(
            L.icon({
              iconUrl: require("@/assets/icons/png/wqMonitor.png"),
              iconSize: [35, 42],
              popupAnchor: [0, -20],
            })
          );
        }
      });
    },
  },
};
</script>

<style lang="scss" scoped>
.home {
  padding: 0px;
  width: 100%;
  height: calc(100vh - 2.1rem);
  display: flex;
  flex-direction: column;
}
.head {
  padding: 16px;
  width: 100%;
  height: 80px;
  display: inline-flex;
  align-items: center;
  gap: 16px;
  border: 1px solid #ebeef5;
  border-radius: 4px;
}
</style>
